const QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
const log = require('../../log.js')
const {
  formatTime,
  changeTime,
  formatNumber
} = require('../../utils/util.js');
const {
  toAttend,
  getTime,
  myAttendClasses,
  WXAboutMe
} = require('../../api/geData.js')
const {
  globalData,
  getUserInfo
} = getApp();
let qqMapSdk;
Page({
  data: {
    titleChoose: true, // 标题样式切换
    courseData: {}, // 考勤课程数据
    userInfo: {}, // 个人信息
    showCourseCover: false, // 控制课程蒙版
    today: '2018-8-18',
    showIndex: 1, //控制没有考勤跟没有统计页面的数据
    formerIndex: 0,
    showClockTemplate: false,
    courseD: [],
    courseList: [ // 课程列表
      {
        courseName: '初级课程-1802',
        date: '2018-07-10',
        showTick: false, // 考勤班级 蒙版层控件打√
        add: '成都国科一教室',
        time: '19:00',
        beginTime: '1534417200000', // 上课打卡时间
        id: '1',
        showClockIn: true, // 显示打卡按钮
        lateBool: null, // 是否迟到
        canClock: null, // 是否能不能打卡
        className: 'skyblue', // 按钮颜色
        text: '上课打卡', // 按钮上文字
        bottomText: '你已进入考勤范围内',
      }
    ],
    finish: 0,
    attendData: [],
    noAttend: [],
    hasAttend: [],
    countBool: true,
    hasNoCourse: false,
    todyNoCourse: false,
    hasNoClass: false,
    attendPhoto:'',
    localAddress: wx.getStorageSync('localAddress')
  },

  onLoad: function(options) {
    let getUserInfo = wx.getStorageSync("userInfo"),
      that = this
    
    clearTimeout(globalData.timer)
    if (!getUserInfo){
      wx.setStorageSync('share', {
        isShare: true,
        path: '../../attendance/attendance'
      })
      wx.reLaunch({
        url: '../login/login/login',
      })
    }

    this.setData({
      today: wx.getStorageSync('time')
    })

    if (Object.keys(globalData.userInfo).length == 0) {
      WXAboutMe(getUserInfo.cluesOrStuId, getUserInfo.type).then(res => {
        log.info('WXAboutMe',res)
        this.setData({
          userInfo: res.info
        })
      })
    }
    qqMapSdk = new QQMapWX({
      key: 'WX7BZ-5PI66-ZKGSD-ET5VF-ZC3RZ-TFBVB'
    })
    // this.getLocalAdd()
  },
  onHide(){
    clearTimeout(globalData.timer)
  },
  
  onShow(){
    // wx.showLoading({
    //   title: '正在获取数据',
    //   mask:true
    // })
    let pho=globalData.userInfo.photo
    // console.log(pho)
    if(pho==undefined)
    {
      pho = '/images/mine/mine@2x.png'
    }
    let attendFormatphoto = pho.replace(/\s*/g, "")
    this.setData({
      userInfo: globalData.userInfo,
      attendPhoto: pho,
      formerIndex: 0
    })
    let getUserInfo = wx.getStorageSync("userInfo")
    // 获取考勤班级数据
    this.toAttendFn(getUserInfo.cluesOrStuId)
    // if (this.data.showClockTemplate){
    //   let clock = this.selectComponent('#clock')
    //   clock && clock.getTimeFn()
    //   clock && clock.getLocationFn()
      
    // } else {
    //   this.setData({
    //     showClockTemplate: true
    //   })
    // }
    // wx.hideLoading()
  },

  onReady() {
    let courseData = this.data.courseData
    if (courseData.courseName) {
      wx.setNavigationBarTitle({
        title: courseData.courseName
      })
    }

  },

  // 获取定位
  // getLocalAdd() {
  //   let that = this
  //   wx.getLocation({
  //     success: function (res) {
  //       if (res) {
  //         let latitude = res.latitude,
  //           longitude = res.longitude;
  //         qqMapSdk.reverseGeocoder({
  //           location: {
  //             latitude: latitude,
  //             longitude: longitude
  //           },
  //           success: function (res) {
  //             console.log(res)
  //             that.setData({
  //               fieldAddress: res.result.address
  //             })
  //             console.log(that.data.fieldAddress)
  //           }
  //         })
  //       }
  //     },
  //   })
  // },
  // 显示课程列表
  showCourseList(e) {
    if (this.data.courseD.length <= 1) return
    let { courseD, courseData } = this.data;
    courseD.forEach((item, index) => {
      if (item.formalClassId === courseData.formalClassId) {
        this.setData({
          formerIndex: index
        })
      }
    })
    this.setData({
      showCourseCover: true
    })
  },
  closeCover(){
    this.setData({
      showCourseCover: false
    })
  },

  

  // 获取考勤班级数据
  toAttendFn(stuId) {
    let that = this,
      toDay = wx.getStorageSync('time'),
      timestamp = new Date().getTime();
    // timestamp = 1554083901000
    toAttend(stuId, toDay).then(items => {
      log.info('toAttend',items)
      let data = items.attendClasses,
        resData = [],
        NEdistance = items.NEdistance,
        courseList = [];

      // console.log(data)
      that.setData({
        hasNoClass: data.length === 0
      })
      let num = 0,
      len = data.length
      data.map((item, index) => {
        wx.request({
          url: globalData.baseUrl + '/attend/toAttend',
          data: {
            stu_id: stuId,
            formal_class_id: item.formalClassId,
            date: toDay
          },
          method: 'POST',
          header: {
            "Content-Type": "application/json"
          },
          success(das) {
            log.info('/attend/toAttend', das.data.data)
            var res = das.data.data
            if (res.attendDetailList.length == 0){
              num ++
            }
            res.attendDetailList.forEach((val, index) => {
              let data = {};
              data = { ...item, ...val };
              data.value = data.starttime && `${val.starttime}-${val.endtime}` || data.value
              // 循环出打卡距离
              NEdistance.forEach(item => {
                if (item.label = val.distance){
                  data.distance = item.value
                }
              })

              let dataValue = data.value
              let value = (dataValue || '').split('-');
              // 计算出当前时间与课程结束时间差值 课程
              wx.getSystemInfo({
                success(res){
                  if (/iOS/.test(res.system)){
                    toDay = toDay.split('-').join('/')
                  }
                }
              })

              data.todayCalssBegind = new Date(toDay + ' ' + value[0]).getTime();
              data.todayCalssEnd = new Date(toDay + ' ' + value[1]).getTime();
              data.todayCalssEndStamp = new Date(toDay + ' ' + value[1]).getTime();
              data.delta_T = (new Date(toDay + ' ' + value[1]).getTime()) - timestamp;
              data.address = val.address
              data.label = val.label
              data.attendStatus = (timestamp - data.todayCalssEndStamp > 0) && !data.punch_date && '旷课' || null
              courseList.push(data)
            })
            let curData = { ...item}
            curData.attendDetailList = res.attendDetailList
            resData.push(curData)
            if (resData.length == data.length) {
              let filterData = [] ;    
              // 过滤掉已经超时的课程
              if (courseList.length != 1) {
                filterData = courseList.filter(item => item.delta_T > 0)
                filterData.sort((a, b) => a.delta_T - b.delta_T)
              }
              courseList.sort((a, b) => a.delta_T - b.delta_T)
              // filterData 没数据  说明全部为负数
              if (filterData.length == 0){
                filterData.push(courseList[courseList.length-1])
              }
              let againArr = []


              resData.forEach(item =>{
                if (!filterData[0]) return
                if (item.formalClassId == (filterData[0].formalClassId)){
                  item.showTick = true
                  againArr.unshift(item)
                } else {
                  item.showTick = false
                  againArr.push(item)
                }
              })

              that.setData({
                courseList: courseList,
                courseD: againArr
              })

              let noAttendArr = filterData.filter(item =>{
                if (item && !item.punch_date) return item
              })

              let _bool = num == len

              that.setData({
                hasNoCourse: _bool
              })
              if (_bool){
                if (data.length == 1) {
                  that.setData({
                    courseD: data,
                    courseData: {
                      courseName: data[that.data.formerIndex].className
                    }
                  })
                }
                for (let i = 0; i < data.length - 1; i++) {
                  for (let j = 0; j < data.length - i - 1; j++) {
                    if (data[j].classBegin > data[j + 1].classBegin) {
                      let priority = data[j];
                      data[j] = data[j + 1];
                      data[j + 1] = priority;
                    } else if (data[j].classBegin == data[j + 1].classBegin) {
                      if (data[j].classEnd > data[j + 1].classEnd) {
                        let priority = data[j];
                        data[j] = data[j + 1];
                        data[j + 1] = priority;
                      } else if (data[j].classEnd == data[j + 1].classEnd) {
                        if (data[j].formalClassId > data[j + 1].formalClassId) {
                          let priority = data[j];
                          data[j] = data[j + 1];
                          data[j + 1] = priority;
                        }
                      }
                    }

                  }
                }
                that.setData({
                  courseD: data,
                  courseData: {
                    courseName: data[that.data.formerIndex].className
                  }
                })
                that.selectComponent('#allWith').changePage(0, 2)
              }

              that.formatCurData(noAttendArr.length && noAttendArr[0] || filterData[0])
              // that.formatAttend(filterData[0])
              for(let i=0;i<filterData.length;i++)
              {
                if (filterData[i].formalClassId === that.data.courseData.formalClassId) {
                  that.formatAttend(filterData[i])
                }
              }
            }
          }
        })
        // toAttend(stuId, toDay, item.formalClassId).then(res => {
        //   if (res.attendDetailList.length == 0){
        //     num ++
        //   }
        //   res.attendDetailList.forEach((val, index) => {
        //     let data = {};
        //     data = { ...item, ...val };
        //     data.value = data.starttime && `${val.starttime}-${val.endtime}` || data.value
        //     // 循环出打卡距离
        //     NEdistance.forEach(item => {
        //       if (item.label = val.distance){
        //         data.distance = item.value
        //       }
        //     })

        //     let dataValue = data.value
        //     let value = (dataValue || '').split('-');
        //     // 计算出当前时间与课程结束时间差值 课程
        //     wx.getSystemInfo({
        //       success(res){
        //         if (/iOS/.test(res.system)){
        //           toDay = toDay.split('-').join('/')
        //         }
        //       }
        //     })

        //     data.todayCalssBegind = new Date(toDay + ' ' + value[0]).getTime();
        //     data.todayCalssEnd = new Date(toDay + ' ' + value[1]).getTime();
        //     data.todayCalssEndStamp = new Date(toDay + ' ' + value[1]).getTime();
        //     data.delta_T = (new Date(toDay + ' ' + value[1]).getTime()) - timestamp;
        //     data.address = val.address
        //     data.label = val.label
        //     data.attendStatus = (timestamp - data.todayCalssEndStamp > 0) && !data.punch_date && '旷课' || null
        //     courseList.push(data)
        //   })
        //   let curData = { ...item}
        //   curData.attendDetailList = res.attendDetailList
        //   resData.push(curData)
        //   if (resData.length == data.length) {
        //     let filterData = [] ;    
        //     // 过滤掉已经超时的课程
        //     if (courseList.length != 1) {
        //       filterData = courseList.filter(item => item.delta_T > 0)
        //       filterData.sort((a, b) => a.delta_T - b.delta_T)
        //     }
        //     courseList.sort((a, b) => a.delta_T - b.delta_T)
        //     // filterData 没数据  说明全部为负数
        //     if (filterData.length == 0){
        //       filterData.push(courseList[courseList.length-1])
        //     }
        //     let againArr = []

            
        //     resData.forEach(item =>{
        //       if (!filterData[0]) return
        //       if (item.formalClassId == (filterData[0].formalClassId)){
        //         item.showTick = true
        //         againArr.unshift(item)
        //       } else {
        //         item.showTick = false
        //         againArr.push(item)
        //       }
        //     })
           
        //     that.setData({
        //       courseList: courseList,
        //       courseD: againArr
        //     })

        //     let noAttendArr = filterData.filter(item =>{
        //       if (item && !item.punch_date) return item
        //     })

        //     let _bool = num == len

        //     this.setData({
        //       hasNoCourse: _bool
        //     })
        //     if (_bool){
        //       if (data.length == 1) {
        //         this.setData({
        //           courseD: data,
        //           courseData: {
        //             courseName: data[this.data.formerIndex].className
        //           }
        //         })
        //       }
        //       for (let i = 0; i < data.length - 1; i++) {
        //         for (let j = 0; j < data.length - i - 1; j++) {
        //           if (data[j].classBegin > data[j + 1].classBegin) {
        //             let priority = data[j];
        //             data[j] = data[j + 1];
        //             data[j + 1] = priority;
        //           } else if (data[j].classBegin == data[j + 1].classBegin) {
        //             if (data[j].classEnd > data[j + 1].classEnd) {
        //               let priority = data[j];
        //               data[j] = data[j + 1];
        //               data[j + 1] = priority;
        //             } else if (data[j].classEnd == data[j + 1].classEnd) {
        //               if (data[j].formalClassId > data[j + 1].formalClassId) {
        //                 let priority = data[j];
        //                 data[j] = data[j + 1];
        //                 data[j + 1] = priority;
        //               }
        //             }
        //           }

        //         }
        //       }
        //       this.setData({
        //         courseD: data,
        //         courseData: {
        //           courseName: data[this.data.formerIndex].className
        //         }
        //       })
        //       this.selectComponent('#allWith').changePage(0, 2)
        //     }

        //     that.formatCurData(noAttendArr.length && noAttendArr[0] || filterData[0])
        //     that.formatAttend(filterData[0])
        //   }
        // }).catch(err => {
        //   console.log(err)
        // })
      })
    }).catch(err => {
      log.error('toAttend',err)
    })
  },

  formatAttend(filterData){
    let courseList = this.data.courseList;
    // console.log(courseList)
    if (courseList.length == 0) return;
    // 过滤出当前要显示的
    let attendData = courseList.filter(item => item.formalClassId == filterData.formalClassId);
    // 过滤出已经打卡的
    let hasAttend = attendData.filter(item => {
      if (item.punch_date || item.attendStatus){
        item.formatHasAttend = this.formatHasAttend(item)
        return item;
      }
    });
    // 过滤出没有打卡的
    let noAttend = attendData.filter(item => {
      if (!item.punch_date && !item.attendStatus){
        return item;
      }
    })
    // 没有打卡
    // console.log('noAttend')
    // console.log(noAttend)
    // 已经打过卡
    // console.log('hasAttend')
    // console.log(hasAttend)

    this.setData({
      noAttend: noAttend,
      hasAttend: hasAttend,
    })
  },

  // 打卡考勤相关
  formatHasAttend (data) {
    let formatData = {};
    // console.log('data')
    // console.log(data)
    if (data.punch_date){
      formatData.punch_date = /:/.test(data.punch_date) && data.punch_date || formatTime(data.punch_date).split(' ')[1]
    } else {
      formatData.punch_date = null
    }
    formatData.classTime = data.value.split('-')[0];
    formatData.label = data.label == '中' && '下午' || data.label+'上';

    if (data.attendStatus == '旷课'){
      formatData.colorSign = 'red'
      formatData.attendStatus = '旷课'
    } else if (data.punch_date - data.todayCalssBegind > 0){
      formatData.colorSign = 'red'
      formatData.attendStatus = '迟到'
    } else if (data.punch_date - data.todayCalssBegind < 0){
      formatData.colorSign = 'blue'
      formatData.attendStatus = '正常'
    }
    
    return formatData
  },




  // 处理当前时间段的课程数据
  /*
    courseName: '初级课程-1802',
        date: '2018-07-10',
        showTick: false, // 考勤班级 蒙版层控件打√
        add: '成都国科一教室',
        time: '19:00',
        beginTime: '1534417200000', // 上课打卡时间
        id: '1',
        showClockIn: true, // 显示打卡按钮
        lateBool: null, // 是否迟到
        canClock: null, // 是否能不能打卡
        className: 'blue', // 按钮颜色
        text: '上课打卡', // 按钮上文字
        bottomText: '你已进入考勤范围内'
  
  
  */ 
  formatCurData(curData){
    // console.log('curData')
    // console.log(curData)
    if (!curData) return
    let data = {}
    data.courseName = curData.className || curData.courseName 
    data.showTick = true
    data.add = curData.name
    data.value = curData.value
    data.schooltime = data.time = curData.value && curData.value.split('-')[0] || null
    data.punch_date = curData.punch_date && new Date(curData.punch_date).getHours() + ':' + formatNumber(new Date(curData.punch_date).getMinutes()) + ':' + formatNumber(new Date(curData.punch_date).getSeconds())
    data.beginTime = curData.value && changeTime(wx.getStorageSync('time').split('-').join('/'), data.time) || null
    data.id = curData.id || null
    data.label = curData.label
    data.status = curData.status
    data.formalClassId = curData.formalClassId
    data.todayCalssBegind = curData.todayCalssBegind
    data.classBegin = curData.classBegin
    data.classEnd = curData.classEnd
    switch (curData.status) {
      case '8':
        data.showClockIn = true
        data.lateBool = null
        break
      case '0':
        data.showClockIn = true
        data.lateBool = null
        break
      case '1':
        data.showClockIn = false
        data.lateBool = null
        break
      case '2':
        data.showClockIn = false
        data.lateBool = true
        break
      case '6':
        this.setData({
          courseData: {
            courseName: data.courseName
          },
          finish: 1
        })
        this.selectComponent('#withoutPage').changePage(1)
        this.selectComponent('#countPage').getCountData(data)
        return
        break
      case '7':
        this.setData({
          courseData: {
            courseName: data.courseName
          },
          finish: 2
        })
        this.selectComponent('#withoutPage').changePage(2)
        return
        break
      default:
        data.showClockIn = true
    }
    console.log(curData)
    if (curData.fieldAttend == '1' || curData.fieldAttend == '0'){
      data.address_name = curData.address_name
      data.address = curData.address
      data.todayCalssEnd = curData.todayCalssEnd
      data.ne = curData.ne
      data.early_punch_card = curData.early_punch_card || '30'
      data.distance = curData.distance
      data.text = '外勤打卡'
      data.bottomText = '你已进入考勤范围内'
      data.classStyle = 'skyblue'
      data.fieldAttend = curData.fieldAttend
    }else{
      data.address_name = curData.address_name
      data.address = curData.address
      data.todayCalssEnd = curData.todayCalssEnd
      data.ne = curData.ne
      data.early_punch_card = curData.early_punch_card || '30'
      data.distance = curData.distance
      data.text = '上课打卡'
      data.bottomText = '进入范围内即可打卡'
      data.classStyle = 'skyblue'
      data.fieldAttend = curData.fieldAttend
    }
    this.setData({
      courseData: data
    })
    let clock = this.selectComponent('#clock')
        clock && clock.getTimeFn()
        clock && clock.getLocationFn()
    this.selectComponent('#countPage').getCountData(data)
    this.selectComponent('#withoutPage') && this.selectComponent('#withoutPage').changePage(0)
  },

  // 处理数据函数
  formatData(resData) {
    let newSort = [],
      nowCourse = {}

    this.setData({
      courseD: resData
    })
  },


  // 打卡导航切换
  handOver(e) {
    // sign 是 0， 1
    
    let bool = !(e.target.dataset.sign * 1) && true || false
    let index = !(e.target.dataset.sign * 1) && 1 || 2
    this.setData({
      titleChoose: bool,
      showIndex: index
    })

    if (!bool) {
      this.selectComponent('#countPage') && this.selectComponent('#countPage').getCountData(this.data.courseData)
    }
    // if (!this.data.hasNoClass) return
    if (this.data.hasNoCourse) {
      this.selectComponent('#allWith').changePage(0, this.data.titleChoose && 2 || 3)
      return
    }
    

    // 获取without页面调用里面的changePage的方法
    // 如果courseData有数据 without 不会显示不让下面调用without里面的方法
    if (JSON.stringify(this.data.courseData) != "{}") return
    if (this.data.hasNoClass){
      this.selectComponent('#without').changePage(index, this.data.titleChoose && 1 || 3)
    } else {
      this.selectComponent('#without').changePage(index)
    }
    

    

  },


  // 考勤班级选择函数
  chooseCourse(e) {
    let index = e.currentTarget.dataset.index;
    // console.log(index)
    // 点击原来index不请求
    if (this.data.formerIndex == index) {
      this.setData({
        showCourseCover: false
      })
      return
    }

    let timestamp = new Date().getTime(),
      courseD = this.data.courseD,
      courseList = this.data.courseList
    if (courseList.length ===0 && this.data.hasNoCourse){
      this.setData({
        courseData: {
          courseName: courseD[index].className
        },
        showCourseCover: false,
        formerIndex: index
      })
      return
    }

    if (courseD.attendDetailList && !courseD[index].attendDetailList.length){
      this.formatCurData(courseD[index])
      this.setData({
        showCourseCover: false,
        formerIndex: index
      })
      return
    }

    
      // 过滤掉不是选择的课程
    let filterData = courseList.filter(item => courseD[index].formalClassId == item.formalClassId);

    if (filterData.length == 0){

      this.setData({
        courseData: {
          courseName : courseD[index].className,
        },
        showCourseCover: false,
        showIndex: 0,
        formerIndex: index,
        hasNoCourse:true
      })
      //判断是统计还是打卡
      this.selectComponent('#allWith').changePage(0, this.data.titleChoose && 2 || 3)
      return
    }
    else{
      this.setData({
        hasNoCourse: false
      })
    }
      // 过滤掉已经超时的课程
    if (filterData.length != 1){
      
      filterData = filterData.filter(item => item.delta_T > 0)
      filterData.sort((a, b) => a.delta_T - b.delta_T)
    }


    // filterData 没数据  说明全部为负数
    if (filterData.length == 0) {
      let filterCourse = courseList.filter(item => item.formalClassId == courseD[index].formalClassId)

      filterData.push(filterCourse[filterCourse.length-1])
    }
    
    courseD.forEach((item, idx )=> {
      item.showTick = (idx == index) && true || false
    })

    this.setData({
      courseD: courseD,
      showCourseCover: false,
      formerIndex: index
    })
    // console.log('filterData')
    // console.log(filterData)
    let noAttendArr = filterData.filter(item => !item.punch_date);
    this.formatCurData(noAttendArr.length && noAttendArr[0] || filterData[0])
    this.formatAttend(filterData[0])
    
    // 调统计模板里面的getCountData的方法 获取数据
    this.selectComponent('#countPage') && this.selectComponent('#countPage').getCountData(filterData[0])
    this.selectComponent('#clock') && this.selectComponent('#clock').getLocationFn()
  },



  // 子组件触发的函数
  getChildData(eventDetail) {
    let courseList = this.data.courseList,
      childData = eventDetail.detail.childData
    
    courseList.forEach((item, index) => {
      if (item.id == childData.id) {
        courseList[index] = childData
      }
    })
    this.setData({
      courseList: courseList
    })
  },

  /* 用户点击右上角分享*/
  onShareAppMessage: function () {
    return {
      title: '今天你认真学习了么？',//分享内容
      path: 'pages/attendance/attendance?isShare=1',//分享地址
      imageUrl: '/images/attendance/dk_fx.png',//分享图片
    }
  }


})